package Demo77;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 在每个树行中找最大值
 * https://leetcode.cn/problems/hPov7L/submissions/562787308/
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) return ret;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()) {
            int sz = queue.size();
            int maxNum = Integer.MIN_VALUE;
            // 遍历一整层
            for(int i = 0; i < sz; i++) {
                TreeNode node = queue.poll();
                // 计算最大值
                maxNum = Math.max(maxNum, node.val);
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
            }
            ret.add(maxNum);
        }
        return ret;
    }
}